<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>预约规则管理</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text"
          @click="handleAdd"
        >
          新增规则
        </el-button>
      </div>
      
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="规则名称" />
        <el-table-column prop="timeRange" label="可预约时段">
          <template slot-scope="{row}">
            {{ row.startTime }} - {{ row.endTime }}
          </template>
        </el-table-column>
        <el-table-column prop="maxHoursPerBooking" label="最大预约时长(小时)" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="{row}">
            <el-tag :type="row.isEnabled === true ? 'success' : 'info'">
              {{ row.isEnabled === true ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="{row}">
            <el-button 
              type="text" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="text" 
              @click="handleToggleStatus(row)"
            >
              {{ row.isEnabled === true ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="text" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑规则对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible"
      width="500px"
    >
      <el-form 
        ref="ruleForm" 
        :model="ruleForm" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="最大提前天数" prop="maxDaysAhead">
          <el-input-number v-model="ruleForm.maxDaysAhead" :min="1" :max="30" />
          <span class="unit">天</span>
        </el-form-item>
        <el-form-item label="每月最大预约次数" prop="maxBookingsPerMonth">
          <el-input-number v-model="ruleForm.maxBookingsPerMonth" :min="1" :max="100" />
          <span class="unit">次</span>
        </el-form-item>
        <el-form-item label="可预约时段">
          <el-time-picker
            v-model="ruleForm.startTime"
            format="HH:mm"
            placeholder="开始时间"
          />
          <span class="time-separator"> - </span>
          <el-time-picker
            v-model="ruleForm.endTime"
            format="HH:mm"
            placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="最大时长" prop="maxHoursPerBooking">
          <el-input-number 
            v-model="ruleForm.maxHoursPerBooking" 
            :min="1" 
            :max="24"
          />
          <span class="unit">小时</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'BookingRules',
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      dialogTitle: '新增规则',
      ruleForm: {
        name: '',
        roomId: undefined,
        maxDaysAhead: 7,
        maxHoursPerBooking: 4,
        maxBookingsPerMonth: 30,
        startTime: '',
        endTime: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入规则名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        roomId: [
          { required: true, message: '请选择自习室', trigger: 'change' }
        ],
        maxHoursPerBooking: [
          { required: true, message: '请输入最大预约时长', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      try {
        const res = await request({
          url: '/api/booking-rule/',
          method: 'get'
        })
        if (res.code === 200) {
          this.tableData = res.data
        }
      } catch (error) {
        this.$message.error('获取规则列表失败')
      }
    },
    handleAdd() {
      this.dialogTitle = '新增规则'
      this.ruleForm = {
        name: '',
        roomId: undefined,
        maxDaysAhead: 7,
        maxHoursPerBooking: 4,
        maxBookingsPerMonth: 30,
        startTime: '',
        endTime: '',
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑规则'
      this.ruleForm = {
        ...row,
        startTime: new Date(`2000-01-01T${row.startTime}`),
        endTime: new Date(`2000-01-01T${row.endTime}`)
      }
      this.dialogVisible = true
    },
    async handleToggleStatus(row) {
      try {
        const res = await request({
          url: `/api/booking-rule/${row.id}/status`,
          method: 'put',
          data: {
            isEnabled: !row.isEnabled
          }
        })
        if (res.code === 200) {
          this.$message.success('状态更新成功')
          this.getList()
        }
      } catch (error) {
        this.$message.error('状态更新失败')
      }
    },
    async handleDelete(row) {
      this.$confirm('确认删除该规则吗？删除后不可恢复', '警告', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request({
            url: `/api/booking-rule/${row.id}`,
            method: 'delete'
          })
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },
    async handleSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const formData = {
            ...this.ruleForm,
            startTime: this.formatTime(this.ruleForm.startTime),
            endTime: this.formatTime(this.ruleForm.endTime)
          }
          
          if (this.ruleForm.id) {
            this.updateRule(formData)
          } else {
            this.addRule(formData)
          }
        }
      })
    },
    async addRule(data) {
      try {
        const res = await request({
          url: '/api/booking-rule/',
          method: 'post',
          data
        })
        if (res.code === 200) {
          this.$message.success('添加成功')
          this.dialogVisible = false
          this.getList()
        }
      } catch (error) {
        this.$message.error('添加失败')
      }
    },
    async updateRule(data) {
      try {
        const res = await request({
          url: `/api/booking-rule/updateRule`,
          method: 'post',
          data
        })
        if (res.code === 200) {
          this.$message.success('更新成功')
          this.dialogVisible = false
          this.getList()
        }
      } catch (error) {
        this.$message.error('更新失败')
      }
    },
    formatTime(date) {
      if (!date) return ''
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${hours}:${minutes}:00`
    }
  }
}
</script>

<style scoped>
.time-separator {
  margin: 0 10px;
}

.unit {
  margin-left: 10px;
  color: #606266;
}

.dialog-footer {
  text-align: right;
}
</style> 